package leetcode;

import java.util.List;

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
public class LeetCode002 {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode preNode = new ListNode();
        ListNode curNode = preNode;

        int carry = 0, rem, a, b;
        while (l1 != null || l2 != null) {
            a = (l1 != null) ? l1.val : 0;
            b = (l2 != null) ? l2.val : 0;

            int sum = a + b + carry;

            rem = sum % 10 ;
            carry = sum / 10;

            curNode.next = new ListNode(rem);
            curNode = curNode.next;

            if (l1 != null) {
                l1 = l1.next;
            }
            if (l2 != null) {
                l2 = l2.next;
            }
        }
        if (carry == 1) {
            curNode.next = new ListNode(carry);
        }
        return preNode.next;
    }

    public static void print(ListNode node) {
        while (node != null) {
            System.out.print("->" + node.val);
            node = node.next;
        }
        System.out.println();
    }
}
